var Photo = require('../models/Photo');
var path = require('path');
var fs = require('fs');
var join = path.join;

var photos = [];
photos.push({
    name: 'Node.js Logo',
    path: 'http://nodejs.org/images/logos/nodejs-green.png'
});
photos.push({
    name: 'Ryan Speaking',
    path: 'http://nodejs.org/images/ryan-speaker.jpg'
});

exports.list = function(req, res) {
    Photo.find( function(photos) {
        res.render('photos', {
            title: 'Photos',
            photos: photos
        });
    });
};

exports.form = function(req, res) {
    res.render('photos/upload', {
        title: 'Photo upload'
    });
};


exports.submit = function(dir) {
    return function(req, res, next) {
        var img = req.files[0];
        var name = req.body.name || img.originalname;
        var path = join(dir, name);
        fs.rename(img.path, path, function(err) {
            if (err) return next(err);
            Photo.create({
                name: name,
                path: name
            });
            res.redirect('/photos');              // 重定向URL
        });
    };
};

exports.download = function(dir) {
    return function(req, res, next) {
        var id = req.params.id;
        Photo.findById(id, function(err, photo) {
            if (err) return next(err);
            var path = join(dir, photo.name);
            res.sendfile(path, function(error) {
                if (error) return next(error);
                console.log('SendFile: ' + path + ' OK!!!');
            });
//            res.sendfile(path);

            // 第二个参数设定下载时提示的文件名
            res.download(path, photo.name);
        });
    };
};


























